package com.dzu.easy;

/**
 * @author ZhaoDong
 * @date 2022/10/31 10:48
 * @description 482. 密钥格式化
 */
public class Test482 {

    public static void main(String[] args) {

        System.out.println(licenseKeyFormatting("2-5g-3-J", 2));

    }

    // optimize
    public static String licenseKeyFormatting2(String s, int k) {
        StringBuilder sb = new StringBuilder();
        for (int i = s.length() - 1, cnt = 0; i >= 0; i--) {
            if (s.charAt(i) == '-') {
                continue;
            }
            // less time
            if (cnt == k && (cnt = 0) >= 0) {
                sb.append("-");
            }
            sb.append(s.charAt(i));
            cnt++;
        }
        return sb.reverse().toString().toUpperCase();
    }




    public static String licenseKeyFormatting(String s, int k) {
        StringBuffer sb = new StringBuffer();
        String replace = s.replace("-", "").toUpperCase();


        int length = replace.length();

        for (int i = length - 1; i >= 0; i--) {
            int j = length - i;
            sb.append(replace.charAt(i));

            if (j > 0 && j < length && j % k == 0) {

                sb.append("-");
            }

        }

        return sb.reverse().toString();
    }
}
